const {mongoose, Schema} = require('./index')
const config = require('../config')

//ref 对应的是注册过的model
let models = {
	Token: mongoose.model('Token', new Schema({
		userId: String,
		value: String,
		createTime: {
			type: Date,
			default: Date.now
		},
		expire: {
			type: Number,
			default: config.tokenDestoryExpires
		}
	})),
	User: mongoose.model('User', new Schema({
		email: String,
		password: String,
		adminAuth: {
			type: Number,
			default: 0
		}
	})),
	Category: mongoose.model('Category', new Schema({
		name: String,
		type: String,
		sort: {
			type: Number,
			default: 0
		}
	})),
	Course: mongoose.model('Course', new Schema({
		name: String,
		category: {
			type: Schema.Types.ObjectId,
			ref: 'Category'
		},
		user: {
			type: Schema.Types.ObjectId,
			ref: 'User'
		},
		createTime: {
			type: Date,
			default: Date.now
		},
		learnCount: {
			type: Number,
			default: 0
		},
		status: {
			type: String,
			default: 'updating'
		},
		sort: {
			type: Number,
			default: 0
		}
	})),
}

//添加默认用户（拥有所有权限）
models.User.findOne({email:'724953302@qq.com'},(err,doc)=>{
    if(!doc){
        new models.User({
            email: '724953302@qq.com',
            password: 'zp0117!',
            adminAuth: 1
        }).save((err)=>{
            if(err)console.log('初始化（创建）管理员失败！--[In path:"~Server/mongodb/models.js"]', err.message)
            else console.log('成功创建管理员：724953302@qq.com。--[MongoDB]')
        })
    }else if(doc.adminAuth!=1){
        models.User.update({email: '724953302@qq.com'}, {adminAuth: 1, password:'admin123'}, (err, row)=>{
            if(err) console.log('管理员授权失败！--[In path:"~Server/mongodb/models.js"]')
        })
    }
})

module.exports = models